package com.zzw.redisson;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author Administrator
 */
@Configuration
@EnableConfigurationProperties(RedissonProperties.class)
public class RedissonConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = "redisson", name = "host")
    public RedissonClient redissonClient(RedissonProperties redissonProperties) {
        if (redissonProperties.getMode().equals(RedissonProperties.Mode.cluster)) {
            Config config = new Config();
            config.useClusterServers().addNodeAddress(redissonProperties.getHost().split(","))
                    .setPassword(redissonProperties.getPassword());
            return Redisson.create(config);
        }
        Config config = new Config();
        config.useSingleServer().setAddress(redissonProperties.getHost()).setPassword(redissonProperties.getPassword()).setDatabase(redissonProperties.getDatabase());
        return Redisson.create(config);
    }

    @Bean
    @ConditionalOnBean({RedissonClient.class, StringRedisTemplate.class})
    public RedisHelper redisHelper(RedissonClient redissonClient, StringRedisTemplate stringRedisTemplate) {
        return new RedisHelper(stringRedisTemplate, redissonClient);
    }
}
